/**
 * Created by gongxun on 16/11/15.
 */

var KwxTableStatus = function(){
    var that = new KwxTableMsgStatus();

    //牌桌映像
    that.mTableStatus = null;

    //录像msg
    that.replayMsgs = null;

    //录像type
    that.replayTypes = null;

    //牌桌用户
    that.mTableUsers = {};

    //牌桌结算印象
    that.mTableResults = [];

    //保存所有牌出现次数
    that.mTableCardCount = null;

    //是否是断线重练
    that.isReconnect = false;

    //test
    that.kwxAutoRobot = null;

    that.init = function(){
        that.kwxAutoRobot = new KwxAutoRobot();
    };

    //设置牌桌映像
    that.setTableStatus = function(tableStatus){
        that.mTableStatus = tableStatus;

        //记录是否是断线重连
        if (that.mTableStatus.Step != 0){
            that.isReconnect = false;
        }

        //在卡五星里面才触发
        if (mo.sceneHelper.currentLayerName != "kwx"){
            return;
        }

        that.updateTableStatus();
    };

    //短线重连
    that.setReconnectStatus = function(tableStatus){
        that.mTableStatus = tableStatus;

        //记录是否是断线重连
        if (that.mTableStatus.Step == 0){
            that.isReconnect = true;
        }

        //过滤
        if (that.filterErrorMsg()){
            return;
        }

        //重置
        that.mTableCardCount = null;

        //更新用户信息
        that.updateUserInfo();

        //设置当前操作玩家
        that.setCurrentPlayer();

        //显示当前开口
        that.setOpenCardType();

        //显示自己的吃碰杠胡操作
        that.setTableOperating();

        //更新牌桌step
        mo.kwxTable.updateTableStep(that.mTableStatus.Step);

        //停止用听
        that.stopUseTing();

        //牌桌重绘
        mo.kwxTable.mKwxCardLayer.setReconnectStatus(tableStatus);

        //听牌用户染色 翻牌
        that.showTingUserLightCards();

        //自己手牌的flag
        that.showCardFlag();

        //检测自动出牌
        that.onCheckAutoPlayCard();
    };

    //更新牌桌映象
    that.updateTableStatus = function(){
        //过滤
        if (that.filterErrorMsg()){
            return;
        }

        //重置
        that.mTableCardCount = null;

        //更新用户信息
        that.updateUserInfo();

        //设置当前操作玩家
        that.setCurrentPlayer();

        //显示当前开口
        that.setOpenCardType();

        //显示自己的吃碰杠胡操作
        that.setTableOperating();

        //更新牌桌step
        mo.kwxTable.updateTableStep(that.mTableStatus.Step);

        //停止用听
        that.stopUseTing();

        //打牌相关
        that.updateStep();

        //听牌用户染色 翻牌
        that.showTingUserLightCards();

        //自己手牌的flag
        that.showCardFlag();

        //播放音效
        that.playMusic();

        //检测自动出牌
        that.onCheckAutoPlayCard();
    };

    //更新用户信息
    that.updateUserInfo = function(){
        //牌局结束以后（剩余次数为0，step为0） 不显示用户ui变化
        if (that.mTableStatus.LeftPlayTimes == 0 && that.mTableStatus.Step == 0){
            return;
        }

        //收到大结算了 不处理用户变化
        if (mo.kwxTable.mKwxJuEndedEventkwx != null){
            return;
        }

        if (that.mTableStatus.TableID){
            var seatUser = [that.mTableStatus.SeatUser1, that.mTableStatus.SeatUser2, that.mTableStatus.SeatUser3];
            var infos = [null, null, null];
            for (var i = 0; i < 3; i++){
                infos[that.getViewForLogic(i, that.mTableStatus.MySeat - 1)] = seatUser[i];
                if (seatUser[i] != null){
                    infos[that.getViewForLogic(i, that.mTableStatus.MySeat - 1)].Score = (seatUser[i].Score != null) ? seatUser[i].Score : 0;
                }
            }
            mo.kwxTable.mKwxTableUILayer.setUserInfos(infos);
        }else{
            //录像可能没有
        }
    };

    //更新牌局信息
    that.updateStep = function(){

        if (that.mTableStatus.Step == 0){

        }else if (that.mTableStatus.Step == 1){
            mo.kwxTable.resetTable();
        }
        else if (that.mTableStatus.Step == 2){
            //是否起牌
            var isQipai = false;
            if(!that.mTableStatus.LastAction){
                isQipai = true;
            }else if (that.mTableStatus.LastAction.code == 1){
                isQipai = true;
            }

            if (isQipai){
                //发牌
                var cardss = [[], [], []];
                for (var i = 0; i < 3; i++){
                    var seatUser = that.getTableUserStatskwx(i);
                    var cards = [];
                    if (seatUser){
                        cards = seatUser.HandCards;
                        if (cards.length == 0){
                            for (var j = 0; j < seatUser.LeftCards; j++){
                                cards.push(0);
                            }
                        }
                    }
                    cardss[i] = cards;
                }
                mo.soundHelper.playStartGame();
                mo.kwxTable.setInhandCards(cardss);

                //尝试扔骰子
                var dice1 = parseInt(that.mTableStatus.SZ / 10);
                var dice2 = that.mTableStatus.SZ % 10;
                mo.kwxTable.mKwxTableShanglouLayer.runDices(dice1, dice2);
                return;
            }

            //判断在做什么
            var LastAction = that.mTableStatus.LastAction;
            var LastActionSeat = that.mTableStatus.LastActionSeat - 1;
            LastActionSeat = that.getViewForLogic(LastActionSeat, that.mTableStatus.MySeat - 1);

            var NowSeat = that.mTableStatus.NowSeat - 1;
            NowSeat = that.getViewForLogic(NowSeat, that.mTableStatus.MySeat - 1);

            if (LastAction.code == 7){
                //出牌
                var dealCard = LastAction.Cards1[0];
                var DrawCard = that.mTableStatus.DrawCard;

                //起牌
                if (that.mTableStatus.IsPlayCard){
                    mo.kwxTable.addInhandCard(NowSeat, DrawCard);
                }

                //出牌
                if (that.mTableStatus.LastActionSeat == that.mTableStatus.MySeat){
                    //自己 预处理检测
                    that.checkPredictionCard(LastAction, that.mTableStatus["SeatUser" + that.mTableStatus.MySeat]);
                }else{
                    //其他玩家正常出牌
                    mo.kwxTable.setDealCard(LastActionSeat, dealCard);

                    //提示玩家打出的牌
                    var showDealCard = [0, 0, 0];
                    showDealCard[LastActionSeat] = dealCard;
                    mo.kwxTable.mKwxTableUILayer.mKwxTableResultLayer.showDealCard(showDealCard);
                }
            }else if (LastAction.code == 0){
                //亮听
                var dealCard = LastAction.Cards1[0];
                var DrawCard = that.mTableStatus.DrawCard;

                mo.kwxTable.setDealCard(LastActionSeat, dealCard);

                if (that.mTableStatus.IsPlayCard){
                    mo.kwxTable.addInhandCard(NowSeat, DrawCard);
                }

                //提示玩家打出的牌
                var showDealCard = [0, 0, 0];
                showDealCard[LastActionSeat] = dealCard;
                mo.kwxTable.mKwxTableUILayer.mKwxTableResultLayer.showDealCard(showDealCard);
            }else if (LastAction.code == 2){
                //碰
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0]];
                var openType = 2;

                mo.kwxTable.setOpenCard(LastActionSeat, cardNums, openType);
            }else if (LastAction.code == 4){
                //明杠
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0]];
                var openType = 4;
                var DrawCard = that.mTableStatus.DrawCard;

                mo.kwxTable.setOpenCard(LastActionSeat, cardNums, openType);
                mo.kwxTable.addInhandCard(NowSeat, DrawCard);
            }else if (LastAction.code == 5){
                //暗杠
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0]];
                var openType = 5;
                var DrawCard = that.mTableStatus.DrawCard;

                mo.kwxTable.setOpenCard(LastActionSeat, cardNums, openType);
                mo.kwxTable.addInhandCard(NowSeat, DrawCard);
            }else if (LastAction.code == 6){
                var cardNums = [LastAction.Cards1[0]];
                //补杠

                var openType = 6;
                var DrawCard = that.mTableStatus.DrawCard;

                mo.kwxTable.setOpenCard(LastActionSeat, cardNums, openType);

                if (LastActionSeat == NowSeat){
                    //不一致说明 有人通过补杠胡牌了
                    mo.kwxTable.addInhandCard(NowSeat, DrawCard);
                }
            }else if (LastAction.code == 8){
                //过
                var DrawCard = that.mTableStatus.DrawCard;

                if (that.mTableStatus.IsPlayCard){
                    mo.kwxTable.addInhandCard(NowSeat, DrawCard);
                }
            }else if (LastAction.code == 3){
                //清理牌桌
                // mo.kwxTable.resetTable();
                //牌桌重绘
                // mo.kwxTable.mKwxCardLayer.setReconnectStatus(that.mTableStatus);
            }

            //检测错误 重新绘制牌桌
            that.checkTableDisplay();
        }
    };

    //检测显示数据和录像是否一直 不一致刷新整个牌桌
    that.checkTableDisplay = function(){
        if (that.mTableStatus.Step == 2){

            var isUnanimous = true;
            for (var seat = 0; seat < 3; seat++){
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                //服务端数据
                var seatUser = that.mTableStatus["SeatUser" + (logicSeat + 1)];
                //本地显示数据
                var player = mo.kwxTable.mKwxCardLayer.mPlayers[seat];

                if (seatUser != null){
                    //检测手牌
                    if (player.inhandCards.length != seatUser.LeftCards){
                        isUnanimous = false;
                        break;
                    }

                    //检测打出牌
                    if (player.dealCards.length != seatUser.PlayCards.length){
                        isUnanimous = false;
                        break;
                    }

                    //检测开口牌
                    if (player.openCards.length != seatUser.Groups.length){
                        isUnanimous = false;
                        break;
                    }
                }

            }

            if (!isUnanimous){
                cc.log("检测到不一致了 开始重绘手牌了");
                mo.kwxTable.resetTable();
                mo.kwxTable.mKwxCardLayer.setReconnectStatus(that.mTableStatus);
            }
        }
    };

    //设置当前操作玩家
    that.setCurrentPlayer = function(){
        var seat = 0;
        var timeleft = (that.mTableStatus.NextActionTimeOut != null ? that.mTableStatus.NextActionTimeOut : 10);

        var NowSeat = that.mTableStatus.NowSeat;
        if (NowSeat.length == 0){
            seat = -1;
        }else if (NowSeat.length == 1){
            seat = that.getViewForLogic(NowSeat[0] - 1, that.mTableStatus.MySeat - 1);
        }else{
            seat = -1;
        }

        //是否有玩家操作
        var isOperating = false;
        if (that.mTableStatus.IsPlayCard != 1){
            isOperating = true;
            if (that.mTableStatus.LastActionSeat == 0){
                seat = that.getViewForLogic(NowSeat[0] - 1, that.mTableStatus.MySeat - 1);
            }else{
                seat = that.getViewForLogic(that.mTableStatus.LastActionSeat - 1 + 1, that.mTableStatus.MySeat - 1);
            }
        }
        mo.kwxTable.setCurrentPlayer(seat, isOperating);
    };

    //显示当前开口
    that.setOpenCardType = function(){
        if (that.mTableStatus.Step != 2){
            return;
        }
        var LastAction = that.mTableStatus.LastAction;
        if (LastAction){
            var types = [-1, -1, -1];
            var LastActionSeat = that.mTableStatus.LastActionSeat - 1;
            LastActionSeat = that.getViewForLogic(LastActionSeat, that.mTableStatus.MySeat - 1);

            if (LastAction.code == 0 ||
                LastAction.code == 2 ||
                LastAction.code == 3 ||
                LastAction.code == 4 ||
                LastAction.code == 5 ||
                LastAction.code == 6
            ){
                types[LastActionSeat] = LastAction.code;
                if (LastAction.code == 3){
                    //找到自摸的情况 为33
                    var isZimo = false;
                    if (LastAction.Cards2.length > 0){
                        isZimo = LastAction.Cards2[LastAction.Cards2.length - 1] == 0;
                    }
                    types[LastActionSeat] = isZimo ? 33 : 3;
                }
                mo.kwxTable.mKwxTableUILayer.mKwxTableResultLayer.showResult(types);
            }
        }
    };

    //显示自己的吃碰杠胡操作
    that.setTableOperating = function(){
        var myUseActionRequest = [];
        var isMyOperating = false;

        for(var i = 0; i < that.mTableStatus.NowSeat.length; i++){
            if (that.mTableStatus.NowSeat[i] == that.mTableStatus.MySeat){
                isMyOperating = true;
                break;
            }
        }

        if (isMyOperating){
            //可以碰杠
            var seatUser = that.getTableUserStatskwx(0);
            for (var i = 0; i < seatUser.NewActionList.length; i++){
                var ActionRequestkwxItem = seatUser.NewActionList[i];
                var code = ActionRequestkwxItem.code;
                if (code == 0 || code == 2 || code == 3 || code == 4 || code == 5 || code == 6 || code == 8){
                    myUseActionRequest.push(ActionRequestkwxItem);
                }
            }
            if (myUseActionRequest.length == 0){
                isMyOperating = false;
            }
        }

        //通知ui
        mo.kwxTable.mKwxTableUILayer.mKwxTableOperatingLayer.showOperating(isMyOperating, myUseActionRequest);
    };

    //显示听牌的用户亮的牌
    that.showTingUserLightCards = function(){
        if (that.mTableStatus.Step != 2){

            //停止显示亮听
            for (var i = 0; i < 3; i++){
                mo.kwxTable.mKwxTableUILayer.setShowTing(i, []);
            }

            return;
        }

        //自己的信息
        var seatUserMy = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
        var isMyOpenTing = (seatUserMy.OpenTing == true);

        //翻开其他玩家亮的牌
        for (var i = 0; i < 3; i++) {
            var seatUser = that.getTableUserStatskwx(i);
            if (seatUser == null){
                continue;
            }

            var liangCardNums = [];
            if (seatUser.OpenTing){
                liangCardNums = seatUser.OpenCards;
                mo.kwxCardHelper.sortForNum(liangCardNums);
            }
            mo.kwxTable.mKwxCardLayer.setLiangCard(i, liangCardNums);
        }

        //显示玩家听牌列表UI
        for (var i = 0; i < 3; i++) {
            var seatUser = that.getTableUserStatskwx(i);
            if (seatUser == null){
                continue;
            }

            var tingCardNums = [];
            if (seatUser.OpenTing){
                tingCardNums = seatUser.TingCards;
                tingCardNums = mo.gameHelper.getUniqueArray(tingCardNums);
                tingCardNums.sort();
            }
            mo.kwxTable.mKwxTableUILayer.setShowTing(i, tingCardNums);
        }


        ///自己不能打出的牌 和自己亮的牌
        //1如果自己没有听 所有手牌不能打 就让所有牌都能打
        //2设置自己手牌中不能打的牌和亮出的牌
        var selfNotPlayCardNums = [];
        var selfTingCardNums = [];
        var myIsTing = false;
        for (var i = 0; i < 3; i++){
            var seatUser = that.getTableUserStatskwx(i);
            if (seatUser == null){
                continue;
            }

            if (i == 0){
                //自己亮的牌
                if (seatUser.OpenTing){
                    myIsTing = true;
                    selfNotPlayCardNums = mo.kwxCardHelper.allBasicLawCardNums;
                    selfTingCardNums = seatUser.OpenCards;
                }
            }else{
                //自己不能打的牌
                if (seatUser.OpenTing){
                    selfNotPlayCardNums = selfNotPlayCardNums.concat(seatUser.TingCards);
                }
            }
        }
        selfNotPlayCardNums = mo.gameHelper.getUniqueArray(selfNotPlayCardNums);
        //1如果自己没有听 所有手牌都不能打就 把所有手牌变成可以打
        if (!myIsTing){
            var myInhandCardNums = [];
            for (var i = 0; i < mo.kwxTable.mKwxCardLayer.mPlayers[0].inhandCards.length; i++){
                myInhandCardNums.push(mo.kwxTable.mKwxCardLayer.mPlayers[0].inhandCards[i].mCardNum);
            }
            myInhandCardNums = mo.gameHelper.getUniqueArray(myInhandCardNums);
            if (mo.gameHelper.getContainArrayAndReturnLeft(selfNotPlayCardNums, myInhandCardNums)[0]){
                selfNotPlayCardNums = [];
            }
        }
        //2设置自己手牌中不能打的牌和亮出的牌
        mo.kwxTable.mKwxCardLayer.mPlayers[0].selfNotPlayCardNums = selfNotPlayCardNums;
        mo.kwxTable.mKwxCardLayer.mPlayers[0].selfTingCardNums = selfTingCardNums;
        mo.kwxTable.mKwxCardLayer.mPlayers[0].startSetInhandCardColor();


        //自己听胡的时候 自己起牌的话就把起到的牌设置成白色
        if (myIsTing && that.mTableStatus.NowSeat.length == 1 &&
            that.mTableStatus.NowSeat[0] == that.mTableStatus.MySeat){
            if (that.mTableStatus.IsPlayCard){
                var lastIndex = mo.kwxTable.mKwxCardLayer.mPlayers[0].inhandCards.length - 1;
                if (lastIndex >= 0){
                    mo.kwxTable.mKwxCardLayer.mPlayers[0].inhandCards[lastIndex].resetCardColor();
                }
            }
        }

        //翻开玩家扣牌
        for (var i = 1; i < 3; i++) {
            var seatUser = that.getTableUserStatskwx(i);
            if (seatUser == null){
                continue;
            }

            var kouCardNums = [];
            if (seatUser.OpenTing){
                for (var j = 0; j < 1; j++){
                    kouCardNums.push(999);
                }
                mo.kwxCardHelper.sortForNum(kouCardNums);
            }
            mo.kwxTable.mKwxCardLayer.setKouCard(i, kouCardNums);
        }

        //如果自己亮了牌 就显示其他玩家手牌的值
        // if (isMyOpenTing){
        //     //翻开玩家扣牌
        //     for (var i = 1; i < 3; i++) {
        //         var seatUser = that.getTableUserStatskwx(i);
        //         var handCardNums = seatUser.HandCards;
        //
        //         //判断这个玩家是否起了牌
        //         var DrawCard = that.mTableStatus.DrawCard;
        //         var nowSeat = -1;
        //         if (that.mTableStatus.NowSeat.length > 0){
        //             nowSeat = that.getViewForLogic(that.mTableStatus.NowSeat[0] - 1, that.mTableStatus.MySeat - 1);
        //         }
        //         if (mo.kwxCardHelper.getCardNumIsBasicLaw(DrawCard) &&
        //             nowSeat == i
        //         ){
        //             //起牌 要拿出最后一张再排序
        //             var index = mo.gameHelper.findValueForArray(handCardNums, DrawCard);
        //             if (index != null){
        //                 handCardNums.splice(index, 1);
        //                 mo.kwxCardHelper.sortForNum(handCardNums);
        //                 handCardNums.push(DrawCard);
        //             }else{
        //                 mo.kwxCardHelper.sortForNum(handCardNums);
        //             }
        //         }else{
        //             //没有起牌直接排序
        //             mo.kwxCardHelper.sortForNum(handCardNums);
        //         }
        //
        //         mo.kwxTable.mKwxCardLayer.setLiangedShowHandCard(i, handCardNums);
        //     }
        // }else{
        //     //翻开玩家扣牌
        //     for (var i = 1; i < 3; i++) {
        //         var seatUser = that.getTableUserStatskwx(i);
        //         var kouCardNums = [];
        //         if (seatUser.OpenTing){
        //             for (var j = 0; j < 1; j++){
        //                 kouCardNums.push(999);
        //             }
        //             mo.kwxCardHelper.sortForNum(kouCardNums);
        //         }
        //         mo.kwxTable.mKwxCardLayer.setKouCard(i, kouCardNums);
        //     }
        // }
    };

    that.showCardFlag = function(){
        if (that.mTableStatus.Step != 2){

            //停止显示flag
            mo.kwxTable.mKwxCardLayer.mPlayers[0].setInhandCardFlag([], []);

            return;
        }

        var weixianNums = [];
        var liangNums = [];
        var kouNums = [];
        for (var i = 0; i < 3; i++){
            var seatUser = that.getTableUserStatskwx(i);
            if (seatUser == null){
                continue;
            }

            if (i == 0){
                //自己亮的牌
                if (seatUser.OpenTing){
                    liangNums = seatUser.OpenCards;

                    for (var j = 0; j < seatUser.KouCards.length; j++){
                        kouNums.push(seatUser.KouCards[j]);
                        kouNums.push(seatUser.KouCards[j]);
                        kouNums.push(seatUser.KouCards[j]);
                    }

                    //把亮的牌放到最前面 切排序
                    mo.kwxTable.mKwxCardLayer.mPlayers[0].sortTingCardAndTurn(liangNums);
                }
            }else{
                //自己不能打的牌
                if (seatUser.OpenTing){
                    weixianNums = weixianNums.concat(seatUser.TingCards);
                }
            }
        }
        weixianNums = mo.gameHelper.getUniqueArray(weixianNums);

        //显示自己听的牌
        var tingNums = that.getMyTingNums();

        mo.kwxTable.mKwxCardLayer.mPlayers[0].mFlagWeixianNums = weixianNums;
        mo.kwxTable.mKwxCardLayer.mPlayers[0].mFlagLiangNums = liangNums;
        mo.kwxTable.mKwxCardLayer.mPlayers[0].mFlagTingNums = tingNums;
        mo.kwxTable.mKwxCardLayer.mPlayers[0].mFlagKouNums = kouNums;
        mo.kwxTable.mKwxCardLayer.mPlayers[0].setInhandCardFlag();
    };


    //检测auto出牌
    that.onCheckAutoPlayCard = function(){
        that.kwxAutoRobot.onCheckAutoPlayCard(that.mTableStatus);
    };

    //返回自己听的牌
    that.getMyTingNums = function(){
        var tingNums = [];
        //TODO
        // if (mo.gameHelper.projectCode == 1) {
        //     var mySeatUser = that.getTableUserStatskwx(0);
        //     for (var i = 0; i < mySeatUser.NewActionList.length; i++) {
        //         var action = mySeatUser.NewActionList[i];
        //         if (action.code == 0) {
        //             var openTingWGS = action.Cg;
        //             for (var j = 0; j < openTingWGS.Cs.length; j++) {
        //                 tingNums.push(openTingWGS.Cs[j]);
        //             }
        //             tingNums = mo.gameHelper.getUniqueArray(tingNums);
        //         }
        //     }
        // }
        var mySeatUser = that.getTableUserStatskwx(0);
        for (var i = 0; i < mySeatUser.NewActionList.length; i++) {
            var action = mySeatUser.NewActionList[i];
            if (action.code == 0) {
                var openTingWGS = action.Cg;
                for (var j = 0; j < openTingWGS.Cs.length; j++) {
                    tingNums.push(openTingWGS.Cs[j]);
                }
                tingNums = mo.gameHelper.getUniqueArray(tingNums);
            }
        }
        return tingNums;
    };

    //返回自己可以胡的牌
    that.getMyHuNums = function(feipai){
        var huNums = [];
        //TODO
        // if (mo.gameHelper.projectCode == 1){
            var mySeatUser = that.getTableUserStatskwx(0);
            for (var i = 0; i < mySeatUser.NewActionList.length; i++){
                var action = mySeatUser.NewActionList[i];
                if (action.code == 0){
                    var openTingWGS = action.Cg;
                    for (var j = 0; j < openTingWGS.Cs.length; j++){
                        var tingNum = openTingWGS.Cs[j];
                        if (tingNum == feipai){
                            //包含废牌对应的所有胡牌情况
                            var winGroups = openTingWGS.Wgss[j];

                            //分解胡牌情况
                            for (var m = 0; m < winGroups.Wg.length; m++){
                                //一种胡牌情况
                                var wg = winGroups.Wg[m];
                                for(var n = 0; n < wg.Cg.length; n++){
                                    var cardGroup = wg.Cg[n];
                                    if (cardGroup.Lznum == 1){
                                        var lzCardNums = mo.kwxCardHelper.getLzDecryptCardNums(cardGroup.GroupType, cardGroup.Cards, cardGroup.Lznum);
                                        huNums = huNums.concat(lzCardNums);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            huNums = mo.gameHelper.getUniqueArray(huNums);
        // }
        return huNums;
    };

    //播放音效
    that.playMusic = function(){
        var LastAction = that.mTableStatus.LastAction;
        if (LastAction == null){
            return;
        }
        var sex = 0;
        if (that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat] != null && that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].user_info != null){
            sex = that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].user_info.sex;
        }

        if (that.mTableStatus.Step == 2){
            if (LastAction.code == 7){
                //出牌
                mo.soundHelper.playMjDeal();

                var dealCard = LastAction.Cards1[0];
                mo.soundHelper.playMjCard(dealCard, sex);

            }else if (LastAction.code == 0){
                //亮听
                mo.soundHelper.playMjLiang(sex);
            }else if (LastAction.code == 2){
                //碰
                mo.soundHelper.playMjPengEffect();

                mo.soundHelper.playMjPeng(sex);
            }else if (LastAction.code == 4){
                //明杠
                mo.soundHelper.playMjPengEffect();

                mo.soundHelper.playMjGang(sex, 4);
            }else if (LastAction.code == 5){
                //暗杠
                mo.soundHelper.playMjPengEffect();

                mo.soundHelper.playMjGang(sex, 5);
            }else if (LastAction.code == 6){
                //补杠
                mo.soundHelper.playMjPengEffect();

                mo.soundHelper.playMjGang(sex, 6);
            }else if (LastAction.code == 8){
                //过
            }else if (LastAction.code == 3){
                //胡
                var isZimo = false;
                if (LastAction.Cards2.length > 0){
                    isZimo = LastAction.Cards2[LastAction.Cards2.length - 1] == 0;
                }
                if (false){
                    if (isZimo){
                        mo.soundHelper.playMjZimo(sex);
                    }else{
                        mo.soundHelper.playMjHu(sex);
                    }
                }
            }
        }
    };

    //获取玩家同ip信息
    that.getPlayerIpEqual = function(){
        var result = [];

        //记录ip
        var ipStruct = {};
        for (var i = 1; i <= 3; i++){
            var seatUser = that.mTableStatus["SeatUser" + i];
            if (seatUser == null){
                continue;
            }

            if (seatUser != null && seatUser.user_info != null){
                var userInfo = seatUser.user_info;
                if (mo.gameHelper.getIsJson(userInfo.DeviceJson)){
                    var deviceJson = JSON.parse(userInfo.DeviceJson);
                    var ip = deviceJson.ip;
                    if (ip != null && ip != "" && ip != "127.0.0.1"){
                        if (ipStruct[ip] == undefined){
                            ipStruct[ip] = [];
                        }
                        ipStruct[ip].push(userInfo.nickname);
                    }
                }
            }
        }

        //分解出出现两次的用户
        for(var key in ipStruct){
            if (ipStruct.hasOwnProperty(key)) {
                if (ipStruct[key].length > 1){
                    var nicks = ipStruct[key];
                    for (var i = 0; i < nicks.length; i++){
                        var item = {};
                        item.nick = nicks[i];
                        item.ip = key;
                        result.push(item);
                    }
                }
            }
        }

        return result;
    };

    //设置录像
    that.setReplayMsg = function(rePlaykwx){
        that.replayMsgs = [];
        that.replayTypes = [];

        //设置录像时候自己的座位号
        var replayMySeat = 1;
        var roundEndedEventkwx = rePlaykwx.Result;
        for(var i = 1; i <= 3; i++){
            if (roundEndedEventkwx["SeatUser" + i] != null){
                if (roundEndedEventkwx["SeatUser" + i].user_info != null){
                    if (roundEndedEventkwx["SeatUser" + i].user_info.userid == mo.gameUserInfo.uid){
                        replayMySeat = i;
                        break;
                    }
                }
            }
        }
        roundEndedEventkwx.MySeat = replayMySeat;

        //排序用的结构体
        var msgStruct = [];

        //牌桌映像数据
        for (var i = 0; i < rePlaykwx.Images.length; i++){
            var tableStatskwx = rePlaykwx.Images[i];
            //修改MySeat
            tableStatskwx.MySeat = replayMySeat;

            var msgid = mo.gameMsgManager.getKwxGameMsgId(1406, 1506);

            var msgItem = {};
            msgItem.key = msgid;
            msgItem.msg = tableStatskwx;
            msgStruct.push(msgItem);

            // that.replayMsgs.push(tableStatskwx);
            // that.replayTypes.push(1406);
        }

        //货币结算数据
        for (var i = 0; i < rePlaykwx.Result.RunTimeResult.length; i++){
            var tableStatskwx = rePlaykwx.Result.RunTimeResult[i];
            var msgid = mo.gameMsgManager.getKwxGameMsgId(1417, 1517);

            var msgItem = {};
            msgItem.key = msgid;
            msgItem.msg = tableStatskwx;
            msgStruct.push(msgItem);
        }

        msgStruct.sort(function(a, b){
            return a.msg.PkgIndex - b.msg.PkgIndex;
        });

        for (var i = 0; i < msgStruct.length; i++){
            that.replayMsgs.push(msgStruct[i].msg);
            that.replayTypes.push(msgStruct[i].key);
        }

        //牌桌结算数据
        that.replayMsgs.push(rePlaykwx.Result);
        that.replayTypes.push(mo.gameMsgManager.getKwxGameMsgId(1408, 1508));
    };

    //播放录像
    that.playReplay = function(){
        if (that.replayMsgs.length > 0){
            var msg = that.replayMsgs.shift();
            var type = that.replayTypes.shift();

            var code06 = mo.gameMsgManager.getKwxGameMsgId(1406, 1506);
            var code08 = mo.gameMsgManager.getKwxGameMsgId(1408, 1508);
            var code17 = mo.gameMsgManager.getKwxGameMsgId(1417, 1517);

            var response = null;
            if (type == code06){
                //牌桌映象
                response = new KwxTableStatskwx();

            }else if (type == code08){
                //牌桌结算
                response = new KwxRoundEndedEventkwx();

            }else if (type == code17){
                //牌桌小结算
                response = new KwxTableRunTimeResultkwx();
            }

            if (response){
                response.msg = msg;
                response.log();
                response.handleMsg(msg);
            }else{
                cc.warn("type:" + type + "未注册");
            }

            if (that.replayTypes.length > 0){
                //小结算在杠牌的前面
                if (type == code17){

                    if (that.replayTypes[0] != code17){
                        //当前是小结算 下次不是小结算 就显示结算
                        that.handlerTableResult();
                    }

                    return that.playReplay();
                }else if(that.replayTypes[0] == code06 && that.replayMsgs[0].Step == 1){
                    return that.playReplay();
                }
            }

            return true;
        }else{
            cc.log("录像播放完毕");
            return false;
        }

    };

    //返回TableUserStatskwx
    that.getTableUserStatskwx = function(viewSeat){
        var seatUsers = [that.mTableStatus.SeatUser1, that.mTableStatus.SeatUser2, that.mTableStatus.SeatUser3];
        var logicSeat = that.getLogicForView(viewSeat, that.mTableStatus.MySeat - 1);

        return seatUsers[logicSeat];
    };

    //处理货币结算
    that.handlerTableResult = function(){
        if (that.mTableResults.length != 0){
            var scores = [0, 0, 0];
            for (var i = 0; i < that.mTableResults.length; i++){
                var item = that.mTableResults[i];
                if (
                    item.ResultType == 1 ||
                    item.ResultType == 2 ||
                    item.ResultType == 3
                ){
                    var addSeat = that.getViewForLogic(item.ToSeat - 1, that.mTableStatus.MySeat - 1);
                    var subSeat = that.getViewForLogic(item.FromSeat - 1, that.mTableStatus.MySeat - 1);
                    var score = item.PayMoney;
                    scores[addSeat] += score;
                    scores[subSeat] -= score;
                }
            }
            that.mTableResults.splice(0, that.mTableResults.length);

            mo.kwxTable.setResultScore(scores);
        }
    };

    //返回剩余的手牌
    that.getLeftCardCount = function(cardNum){
        if (that.mTableCardCount == null){
            that.mTableCardCount = [];
            if (that.mTableStatus.Step == 2){
                for (var seat = 0; seat < 3; seat++){
                    var seatUser = that.getTableUserStatskwx(seat);
                    if (seatUser == null){
                        continue;
                    }

                    //手牌
                    for(var i = 0; i < seatUser.HandCards.length; i++){
                        var num = seatUser.HandCards[i];
                        if (!that.mTableCardCount[num.toString()]){
                            that.mTableCardCount[num.toString()] = 0;
                        }
                        that.mTableCardCount[num.toString()] += 1;
                    }

                    //打出去的牌
                    for(var i = 0; i < seatUser.PlayCards.length; i++){
                        var num = seatUser.PlayCards[i];
                        if (!that.mTableCardCount[num.toString()]){
                            that.mTableCardCount[num.toString()] = 0;
                        }
                        that.mTableCardCount[num.toString()] += 1;
                    }

                    //开口牌
                    for (var i = 0; i < seatUser.Groups.length; i++){
                        var cardGroupkwx = seatUser.Groups[i];
                        for (var j = 0; j < cardGroupkwx.Cards.length; j++){
                            var num = cardGroupkwx.Cards[j];
                            if (!that.mTableCardCount[num.toString()]){
                                that.mTableCardCount[num.toString()] = 0;
                            }
                            that.mTableCardCount[num.toString()] += 1;
                        }
                    }

                    //计算别人亮的牌
                    if (seatUser.HandCards.length == 0){
                        for(var i = 0; i < seatUser.OpenCards.length; i++){
                            var num = seatUser.OpenCards[i];
                            if (!that.mTableCardCount[num.toString()]){
                                that.mTableCardCount[num.toString()] = 0;
                            }
                            that.mTableCardCount[num.toString()] += 1;
                        }
                    }
                }
            }
        }

        var count = 0;
        var key = cardNum.toString();
        if (that.mTableCardCount.hasOwnProperty(key)){
            count = that.mTableCardCount[key];
        }

        return 4 - count;
    };

    //过滤会让游戏错误的信息
    that.filterErrorMsg = function(){
        var isError = false;
        var playerCount = mo.gameMsgManager.kwxGameModel == 1 ? 3 : 2;
        //退桌之前受到 seatUser为null
        if (that.mTableStatus.Step == 2){
            var isNull = false;
            for (var i = 1; i <= playerCount; i++){
                if (that.mTableStatus["SeatUser" + i] == null){
                    isNull = true;
                    break;
                }
            }
            if (isNull){
                isError = true;
            }
        }

        return isError;
    };

    //通过ui的返回玩家视图座位号
    that.getViewSeatForUid = function (uid) {
        var logicIndex = -1;
        for (var i = 0; i < 3; i++){
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser == null){
                continue;
            }

            if (seatUser != null){
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid){
                    logicIndex = i;
                }
            }
        }
        if (logicIndex != -1){
            return that.getViewForLogic(logicIndex, that.mTableStatus.MySeat - 1);
        }else{
            return -1;
        }
    };

    //通过用户id获取用户性别
    that.getSexForUid = function(uid){
        var sex = 0;
        for (var i = 0; i < 3; i++){
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser == null){
                continue;
            }

            if (seatUser != null && seatUser.user_info != null){
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid){
                    sex = seatUser.user_info.sex;
                }
            }
        }
        return sex;
    };

    that.getLogicForView = function(view, myLogicSeat){
        var logic = (view + 3 + myLogicSeat) % 3;
        return logic;
    };

    that.getViewForLogic = function(logic, myLogicSeat){
        var view = (logic + 3 - myLogicSeat) % 3;
        return view;
    };

    that.init();

    return that;
};

mo.kwxTableStatus = new KwxTableStatus();